package org.budo.warehouse.logic.util;

import java.util.Map;

import org.budo.support.lang.util.MapUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.spring.expression.util.SpelUtil;
import org.budo.warehouse.logic.api.DataEntry;
import org.budo.warehouse.service.entity.Pipeline;

/**
 * @author limingwei
 */
public class PipelineUtil {
    /**
     * 可以使用SPEL表达式
     */
    public static String targetTable(Pipeline pipeline, DataEntry dataEntry) {
        Map<String, Object> map = MapUtil.stringObjectMap("pipeline", pipeline, //
                "dataEntry", dataEntry);

        String targetTable = pipeline.getTargetTable();
        if (StringUtil.startsWith(targetTable, "#{")) {
            targetTable = SpelUtil.merge(targetTable, map);
        }

        String targetSchema = pipeline.getTargetSchema();
        if (StringUtil.startsWith(targetSchema, "#{")) {
            targetSchema = SpelUtil.merge(targetSchema, map);
        }

        if (!StringUtil.isEmpty(targetSchema)) {
            return "`" + targetSchema + "`.`" + targetTable + "`";
        }

        return "`" + targetTable + "`";
    }

    public static String destinationName(Pipeline pipeline) {
        Map<String, Object> map = MapUtil.stringObjectMap("pipeline", pipeline);

        String targetTable = pipeline.getTargetTable();
        if (StringUtil.startsWith(targetTable, "#{")) {
            targetTable = SpelUtil.merge(targetTable, map);
        }

        String targetSchema = pipeline.getTargetSchema();
        if (StringUtil.startsWith(targetSchema, "#{")) {
            targetSchema = SpelUtil.merge(targetSchema, map);
        }

        if (!StringUtil.isEmpty(targetSchema)) {
            return targetSchema + "." + targetTable;
        }

        return targetTable;
    }
}